<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>排班管理</el-breadcrumb-item>
            <el-breadcrumb-item>排班查询</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="3">
                    <el-select v-model="queryParam.searchParams[0].value" filterable placeholder="请选择日期类型">
                        <el-option
                            v-for="item in typeList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="8">
                    <div>
                    <el-input placeholder="请输入球场名称"  v-model="queryParam.fastSearch" @keyup.enter.native="getScheduleTemp">
                        <el-button slot="append" icon="el-icon-search" @click="getScheduleTemp"></el-button>
                    </el-input>
                    </div>
                </el-col>
                <el-col :span="3">
                    <div>
                    <el-button type="primary" @click="NewScheduleTemp">添加排班</el-button>
                    </div>
                </el-col>
                <el-col :span="3">
                    <div class="title">
                        <!-- (AI智能排班) -->
                    </div>
                </el-col>
            </el-row>
        </el-card>
        <el-card>

        <!--新增排班对话框-->    
        <el-dialog
            title="新增排班模板信息"
            :visible.sync="dialogAddVisible"
            @close="ReSetDialog"
            width="40%">
            <el-form :model="addScheduleForm" :rules="scheduleFormrules" ref="scheduleFormruleForm" label-width="100px">
                <el-form-item label="场馆名称" prop="gymName">
                     <el-select v-model="addScheduleForm.gymId"  @change="getAreaList" filterable placeholder="请选择">
                        <el-option
                            v-for="item in gymList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="场地名称" prop="areaName">
                    <el-select v-model="addScheduleForm.areaId" @change="getCourtList" filterable placeholder="请选择">
                        <el-option
                            v-for="item in areaList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="球场名称" prop="courtName">
                    <el-select v-model="addScheduleForm.courtId" filterable placeholder="请选择">
                        <el-option
                            v-for="item in courtList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="序号" prop="sortId">
                    <el-input-number v-model="addScheduleForm.sortId" :min="0" :max="30" label="请选择显示序号"></el-input-number>
                </el-form-item>
                <el-form-item label="时间起" prop="startTime">
                    <el-input v-model="addScheduleForm.startTime"></el-input>
                </el-form-item>
                <el-form-item label="时间止" prop="endTime">
                    <el-input v-model="addScheduleForm.endTime"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input-number v-model="addScheduleForm.price" :min="1" :max="9999" label="请输入价格"></el-input-number>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="addScheduleForm.type" filterable placeholder="请选择类型">
                        <el-option
                            v-for="item in typeList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="启用" prop="type">
                    <el-switch v-model="addScheduleForm.enabled">
                    </el-switch>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="CloseAddScheduleTemp">取 消</el-button>
                <el-button type="primary" @click="AddScheduleTemp">确 定</el-button>
            </span>
        </el-dialog> 

        <!--修改排班对话框-->
        <el-dialog
            title="修改排班模板信息"
            :visible.sync="dialogUpdVisible"
            @close="ReSetDialog"
            width="40%">
            <el-form :model="scheduleForm" :rules="scheduleFormrules" ref="scheduleFormruleForm" label-width="100px">
                <el-form-item label="场馆名称" prop="gymName">
                    <el-input v-model="scheduleForm.gymName" disabled></el-input>
                </el-form-item>
                <el-form-item label="场地名称" prop="areaName">
                    <el-input v-model="scheduleForm.areaName" disabled></el-input>
                </el-form-item>
                <el-form-item label="球场名称" prop="courtName">
                    <el-input v-model="scheduleForm.courtName" disabled></el-input>
                </el-form-item>
                <el-form-item label="序号" prop="sortId">
                    <el-input v-model="scheduleForm.sortId"></el-input>
                </el-form-item>
                <el-form-item label="时间起" prop="startTime">
                    <el-input v-model="scheduleForm.startTime"></el-input>
                </el-form-item>
                <el-form-item label="时间止" prop="endTime">
                    <el-input v-model="scheduleForm.endTime"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input v-model="scheduleForm.price"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <!-- <el-input v-model="scheduleForm.type"></el-input> -->
                    <el-select v-model="scheduleForm.type" filterable placeholder="请选择类型">
                        <el-option
                            v-for="item in typeList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="CloseUpdScheduleTemp">取 消</el-button>
                <el-button type="primary" @click="UpdateScheduleTemp">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 外层列表 -->
        <el-table
                :data="this.scheduleList"
                border
                stripe
                style="width: 100%">
                <el-table-column
                    type="index"
                    label="#">
                </el-table-column>
                <el-table-column
                    prop="gymName"
                    label="场馆名称">
                </el-table-column>
                <el-table-column
                    prop="areaName"
                    label="场地名称">
                </el-table-column>
                <el-table-column
                    prop="courtName"
                    label="球场名称">
                </el-table-column>
                <el-table-column
                    prop="sortId"
                    label="序号">
                </el-table-column>
                <el-table-column
                    prop="startTime"
                    label="时间起">
                </el-table-column>
                <el-table-column
                    prop="endTime"
                    label="时间止">
                </el-table-column>
                <el-table-column
                    prop="price"
                    label="价格">
                </el-table-column>
                <el-table-column label="启用">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.enabled" @change="UpdateScheduleTempStatue(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="类型">
                    <template slot-scope="scope">
                        <el-tag v-if ="scope.row.type == '1'" type="danger"  effect="dark">工作日</el-tag>
                        <el-tag v-if ="scope.row.type == '2'" type="success" effect="dark">周末</el-tag>
                        <el-tag v-if ="scope.row.type == '3'" type="warning" effect="dark">节假日</el-tag>   
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                        <template slot-scope="scope">
                        <!--{{scope.row}}-->
                        <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                            <el-button type="primary"  icon="el-icon-edit" size="mini" @click="GetScheduleTemp(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger"  icon="el-icon-delete" size="mini" @click="DelScheduleTemp(scope.row)"></el-button>
                        </el-tooltip>
                        <!-- <el-tooltip effect="dark" content="查看排班明细" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="GetScheduleDetail(scope.row)"></el-button>
                        </el-tooltip> -->
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-card>
            <div class="block">
                <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryParam.pagenum"
                :page-sizes="[5,10,20,50]"
                :page-size="queryParam.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
            </div>
        </el-card>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    data(){
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
            callback(new Error('请再次输入密码'));
            } else if (value !== this.scheduleForm.password) {
            callback(new Error('两次输入密码不一致!'));
            } else {
            callback();
            }
        };
        return{
            scheduleList:[],
            gymList:[],
            areaList:[],
            courtList:[],
            courtAllList:[],
            holidayType:1,
            typeList:[{
                "id":1,
                "name":"工作日"
            },{
                "id":2,
                "name":"周末"
            },{
                "id":3,
                "name":"节假日"
            }],
            gymId:"",
            areaId:"",
            courtId:"",
            total:0,
            dialogAddVisible: false,
            dialogUpdVisible: false,
            addScheduleForm:{"areaName": "",
                            "courtId": "",
                            "courtName": "",
                            "createBy": "",
                            "createDate": "",
                            "enabled": true,
                            "startTime": "00:00:00",
                            "endTime": "00:00:00",
                            "gymName": "",
                            "id": "",
                            "price": 0,
                            "sortId": 0,
                            "status": 0,
                            "statusName": "",
                            "type": 1,
                            "updateBy": "",
                            "updateDate": "",
                            "version": ""
                            },
            scheduleForm:[],
            scheduleFormrules:{
                username:[{required:true,message:'请输入用户名',
                            trigger:'blur'},
                            {min:3,max:10,message:'用户名的长度需在3到10个字符之间',
                            trigger:'blur'}],
                password:[{required:true,message:'请输入密码',
                            trigger:'blur'},
                            {min:3,max:10,message:'密码的长度需在3到10个字符之间',
                            trigger:'blur'}],
                ComPassword:[{required:true,message:'请再次输入密码',
                            trigger:'blur'},
                            {validator:validatePass2,
                            trigger:'blur'}],
                mobile:[{required:'true',len:11,message:'请输入正确的手机号码',trigger:'blur'}],
                email:[{required:'true',message:'请输入正确的邮箱号码',trigger:'blur'}],
            },
            userInfoFormrules:{
                mobile:[{required:'true',len:11,message:'请输入正确的手机号码',trigger:'blur'}],
                email:[{required:'true',message:'请输入正确的邮箱号码',trigger:'blur'}], 
            },
            total:0, 
            sizes:1, 
            prev:true, 
            pager:10, 
            next:true, 
            jumper:true,
            queryParam:{
                "direction": "asc",
                "fastSearch": "",
                "field": "",
                "number": 1,
                "searchParams": [
                    {
                        "fieldName": "type",
                        "operator": "eq",
                        "value": "",
                        "value1": ""
                    }
                ],
                "size": 10
            },
            queryGymParam:{
                "direction": "sortId",
                "fastSearch": "",
                "field": "",
                "number": 1,
                "searchParams": [
                    {
                        "fieldName": "status",
                        "operator": "eq",
                        "value": "0",
                        "value1": {}
                    }
                ],
                "size": 100
            },
            queryAreaParam:{
                "direction": "sortId",
                "fastSearch": "",
                "field": "",
                "number": 1,
                "searchParams": [
                    {
                        "fieldName": "status",
                        "operator": "eq",
                        "value": "0",
                        "value1": {}
                    },
                    {
                        "fieldName": "gymId",
                        "operator": "eq",
                        "value": "",
                        "value1": ""
                    },
                ],
                "size": 100
            },
            queryCourtParam:{
                "direction": "sortId",
                "fastSearch": "",
                "field": "",
                "number": 1,
                "searchParams": [
                    {
                        "fieldName": "status",
                        "operator": "eq",
                        "value": "0",
                        "value1": {}
                    },
                    {
                        "fieldName": "areaId",
                        "operator": "eq",
                        "value": "",
                        "value1": ""
                    },
                ],
                "size": 100
            },
            deleteParam:{
                "enabled": true,
                "ids": []
            }
        };
    },
    created(){
        console.log('加载数据')
        this.getScheduleTemp();
        //this.getCourtAllList();
    },
    methods:{
        async getScheduleTemp(){
            console.log('token',window.sessionStorage.getItem('token'))
            //在需要的事件中直接使用
            this.$axios.post(
                'booking/template/list',this.queryParam,
                {
                    headers:{
                        'Authorization': window.sessionStorage.getItem('token')
                    }
                }
            )
            .then(res=>{
                console.log('请求成功',res)

                this.total = res.data.data.totalElements;
                this.pager = res.data.data.totalPages;  
                this.size =  res.data.data.size;
                this.prev =  res.data.data.hasPrevious;
                this.next =  res.data.data.hasNext;
                this.scheduleList = res.data.data.data;
            })
            .catch(Error=>{
                console.log('请求失败',Error)
            })
        },
        handleSizeChange(val){
            this.queryParam.size = val
            this.getScheduleTemp()
        },
        handleCurrentChange(val){
            this.queryParam.number=val
            this.getScheduleTemp()
        },
        async updateUserStatus(userinfo){
            //console.log(userinfo)
            const{data:res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            if(res.meta.status !== 200){
                userinfo.mg_state  != userinfo.mg_state;
                return this.$message.error('更新用户信息失败！')
            }
            else{
                return this.$message.success('更新用户状态成功！')
            }
        },
        //打开更新排班模板信息
        GetScheduleTemp(val){
            this.$axios.get(
                `booking/template/${val}`,
                {
                    headers:{
                        'Authorization': window.sessionStorage.getItem('token')
                    }
                }
            )
            .then(res=>{
                console.log('请求成功',res.data.data)
                this.scheduleForm = res.data.data;

                this.dialogUpdVisible = true
            })
            .catch(Error=>{
                console.log('请求失败',Error)
            })
        },
        //提交更新排班模板信息
        UpdateScheduleTemp(){
            this.$axios.put(
                `booking/template`,this.scheduleForm,
                {
                    headers:{
                        'Accept':'*/*',
                        'Authorization': window.sessionStorage.getItem('token'),
                        'Content-Type':'application/json',
                        'X-Requested-With':'XMLHTTPRequest'
                    }
                }
            )
            .then(res=>{
                console.log('更新成功',res)
                this.dialogUpdVisible = false;

                //刷新数据
                this.getScheduleTemp()
            })
            .catch(Error=>{
                console.log('更新失败',Error)
            })
        },
        //修改状态
        UpdateScheduleTempStatue(val){
            this.scheduleForm= val;
            this.UpdateScheduleTemp();
        },
        //打开新增排班模板信息
        NewScheduleTemp(){
            this.dialogAddVisible = true;
            //获取场馆列表，给列表用
            this.getGymList();
        },
        //提交新增排班模板信息
        AddScheduleTemp(){
                this.$axios.post(
                `booking/template`,this.addScheduleForm,
                {
                    headers:{
                        'Accept':'*/*',
                        'Authorization': window.sessionStorage.getItem('token'),
                        'Content-Type':'application/json',
                        'X-Requested-With':'XMLHTTPRequest'
                    }
                }
            )
            .then(res=>{
                console.log('res',res);
                if(res.data.code==200)
                {
                    this.$message.success("添加成功");
                    this.CloseAddScheduleTemp(); //关闭并清空数据
                    
                    //刷新数据
                    this.getScheduleTemp()
                }
                else
                {
                    console.log('更新失败',res.data.message)
                    this.$message.error(res.data.message);
                }
            })
            .catch(Error=>{
                console.log('更新失败',Error)
            })
        },
        //清空表单
        ReSetDialog(){
            this.$refs.scheduleFormruleForm.resetFields()
        },
        dialogEditClose(){
            // this.$refs.userInfoFormruleForm.resetFields();
        },
        DelScheduleTemp(scheduleInfo){
            this.deleteParam.ids.length = 0;
            this.deleteParam.ids[0]=scheduleInfo.id;

            console.log('deleteParam',this.deleteParam)
            this.$confirm(`是否确认删除【${scheduleInfo.courtName}】序号为【${scheduleInfo.sortId}】【${scheduleInfo.startTime}-${scheduleInfo.endTime}】的排班,请确认?`, '是否继续', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                            this.$axios.delete(
                                `booking/template/delete`,
                                {   
                                    data:this.deleteParam,
                                    headers:{
                                            'Accept':'*/*',
                                            'Authorization': window.sessionStorage.getItem('token'),
                                            'Content-Type':'application/json',
                                            'X-Requested-With':'XMLHTTPRequest'
                                    }
                                }
                            ).then(
                                this.$message.success('删除成功'),
                                //刷新数据
                                this.getScheduleTemp()
                            )
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '已取消删除'
                                });          
                            });
        },
        CloseUpdScheduleTemp(){
            this.gymList=[],
            this.areaList=[],
            this.courtList=[],
            this.gymId="",
            this.areaId="",
            this.courtId="",
            this.dialogUpdVisible = false;
        },
        CloseAddScheduleTemp(){
            this.gymList=[],
            this.areaList=[],
            this.courtList=[],
            this.gymId="",
            this.areaId="",
            this.courtId="",
            this.dialogAddVisible = false;
        },
        //限制只能输入数字
        handleClick(){
            this.num = this.num.replace(/[^\w]/g, '');
        },
        getGymList(){
                this.$axios.post(
                'gym/list',this.queryGymParam,
                {
                    headers:{
                        'Authorization': window.sessionStorage.getItem('token')
                    }
                }
            )
            .then(res=>{
                this.gymList = res.data.data.data;
            })
        },
        getAreaList(){
            this.queryAreaParam.searchParams[1].value =this.gymId;
            this.$axios.post(
                'area/list',this.queryAreaParam,
                {
                    headers:{
                        'Authorization': window.sessionStorage.getItem('token')
                    }
                }
            )
            .then(res=>{
                this.areaList = res.data.data.data;
            })
        },
        getCourtList(){
            console.log('this.areaId',this.areaId);
            this.queryCourtParam.searchParams[1].value =this.areaId;

            this.$axios.post(
                'court/list',this.queryCourtParam,
                {
                    headers:{
                        'Authorization': window.sessionStorage.getItem('token')
                    }
                }
            )
            .then(res=>{
                this.courtList = res.data.data.data;
            })
        },
    },
}
</script>

<style lang="less" scoped>
  .el-breadcrumb{
      margin-bottom: 10px;
      font-size: 14px;
  }
  .el-table-column{
      text-align: center;
  }
  .el-pagination{
      text-align: left;
  }
  .el-form-item{
      margin-right: 50px;
  }
  .title{
      text-align: center;
      margin-top: 6px;
      color: red;
  }

  .el-input-number,
  .el-select,
  .el-switch,
  .el-time-select{
      width: 100%;
  }

  .selectTime{
      width: 100%;
  }
</style>